package com.yksj.healthtalk.ui.home;

import java.util.ArrayList;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SearchAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.MessageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.friend.DoctorMainActivity;
import com.yksj.healthtalk.ui.friend.FriendHttpListener;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.ToastUtil;

public class MyFriendSearchActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener, FriendHttpListener,
		OnRefreshListener2<ListView> {

	private CustomerInfoEntity mCustomerInfoEntity;
	private PullToRefreshListView pullRefreshView;
	private ListView mListView;
	private SearchAdapter mFriendAdapter;
	private ArrayList<CustomerInfoEntity> entities;
	private String DEFAUTPAGEMARK = "-100000";
	private String pageMark = DEFAUTPAGEMARK;// 分页的标记
	final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		public void onReceive(android.content.Context context, Intent intent) {
			if ("y".equalsIgnoreCase(intent.getStringExtra("FLAG"))) {
				ToastUtil.showShort(getApplicationContext(), "转发成功");
				// 好友转发消息需要保存到本地
				Message message = mHandler.obtainMessage();
				message.obj = new MessageEntity[] {(MessageEntity) intent.getSerializableExtra("picture"),
						(MessageEntity) intent.getSerializableExtra("text") };
				message.what = 1;
				mHandler.sendMessage(message);
				requestHttpSendStatus();
			} else {
				ToastUtil.showShort(getApplicationContext(), "转发失败");
			}
		};
	};  
	
	final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 保存消息到数据库
			if (msg.what == 1) {
				final MessageEntity[] entities = (MessageEntity[]) msg.obj;
				new Thread() {
					public void run() {
						ChatUserHelper helper = ChatUserHelper.getInstance();
						List<String> list = mFriendAdapter.getSelectIDs();
						if (entities[0] != null) {
							MessageEntity entity = entities[0];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
						if (entities[1] != null) {
							MessageEntity entity = entities[1];
							for (String id : list) {
								entity.setReceiverId(id);
								helper.insertChatMessage(entity);
							}
						}
					};
				}.start();
			}
		}
	};
	protected void requestHttpSendStatus() {
		HttpRestClient.doHttpActionForImage(getIntent().getStringExtra("picID"), SmartFoxClient.getLoginUserId(),String.valueOf(0) , new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(String content) {
				super.onSuccess(content);
				onBackPressed();
			}
		});
	}
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.salon_others);
		initWidget();
		initData();
	}

	private void initWidget() {
		initTitle();
		titleTextV.setText("搜索患者");
		entities = new ArrayList<CustomerInfoEntity>();
		titleLeftBtn.setOnClickListener(this);
		pullRefreshView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = pullRefreshView.getRefreshableView();
		mFriendAdapter = new SearchAdapter<CustomerInfoEntity>(this, entities);
		mFriendAdapter.setType(0);
		mListView.setAdapter(mFriendAdapter);
		
		if(getIntent().hasExtra("type") && getIntent().getBooleanExtra("type",false)){
			mFriendAdapter.setChangeMode(true);
			titleRightBtn2.setVisibility(View.VISIBLE);
			titleRightBtn2.setOnClickListener(this);
			titleRightBtn2.setText("确定");
		}else{
			mListView.setOnItemClickListener(this);
		}
		
		
	}

	@Override
	public void onStop() {
		unregisterReceiver(mReceiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_REPEAT_STATE);
		registerReceiver(mReceiver, filter);
		super.onStart();
	}
	
	private void initData() {
		pullRefreshView.setRefreshing();
		pullRefreshView.setOnRefreshListener(this);
		mCustomerInfoEntity = (CustomerInfoEntity) getIntent().getExtras().get("mCustomerInfoEntity");
		pageMark = DEFAUTPAGEMARK;
		mCustomerInfoEntity.setId(SmartFoxClient.getLoginUserId());
		mCustomerInfoEntity.setFlag(pageMark);
		FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,MyFriendSearchActivity.this);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageMark = "-100000";
		mCustomerInfoEntity.setFlag(pageMark);
		FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,MyFriendSearchActivity.this);
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		pageMark = mFriendAdapter.getPageFlagMark(false, CustomerInfoEntity.class);
		mCustomerInfoEntity.setFlag(pageMark);
		FriendHttpUtil.getFriends(mCustomerInfoEntity, 0,MyFriendSearchActivity.this);
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		position = position - 1;
		CustomerInfoEntity entity = entities.get(position);
		if (entity.isDoctor()) {
			Intent intent = new Intent(getApplicationContext(),DoctorMainActivity.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		} else {
			FriendHttpUtil.onItemClick(this, entity);
		}
	}

	@Override
	public void onClick(View v) {
		if (v.getTag() != null && v.getTag() instanceof Integer) {
			int position = (Integer) v.getTag();
			CustomerInfoEntity entity = entities.get(position);
			PersonInfoUtil.choiceActivity(entity.getId(), this,String.valueOf(entity.getRoldid()));
		} else {
			switch (v.getId()) {
			case R.id.title_back:
				onBackPressed();
				break;
			case R.id.title_right2:
				SmartFoxClient.sendRepeatToFriend("1",mFriendAdapter.getCusIds(),String.valueOf(getIntent().getStringExtra("picID")) );
				break;
			}
		}

	}

	@Override
	public void responseSuccess(int type, int sourceType,
			ArrayList<CustomerInfoEntity> c) {
		if (pageMark.equals("-100000")) {
			entities.clear();
		}
		entities.addAll(c);
		mFriendAdapter.notifyDataSetChanged();
		pullRefreshView.onRefreshComplete();

	}

	@Override
	public void responseError(int type, int sourceType, String content) {

	}

}
